<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    :showFooter="true"
    v-bind="$attrs"
    :title="getTitle.value"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="90%"
  >
    <BasicForm @register="registerForm">
      <template #taskList>
        <BasicTable @register="registertaskTable" @row-click="handletaskRowClick">
          <!-- <template #fpTextarea="{ record: childRecord }">
          <a-textarea v-model:value="childRecord.textContent" placeholder="请输入" :rows="5" />
      </template> -->
          <template #toolbar>
            <!-- <a-popconfirm
              ok-text=" "
              cancel-text=" "
              placement="bottom"
            >
              <template #icon><question-circle-outlined style="color: red" /></template>
              <template #cancelButton style="color: red">123</template>
                <template #title>
                  <BasicForm @register="registerOperateForm" @submit="handleSubmitOperateForm" />
                </template>

                <a-button type="primary">
                  <Icon icon="simple-line-icons:settings" /> {{ t('批量人员分配') }}
                </a-button>
              </a-popconfirm> -->
              <a-popover v-model:visible="visible" trigger="click">
                <template #content>
                  <BasicForm @register="registerOperateForm" @submit="handleSubmitOperateForm" />
                </template>
                <a-button type="primary">
                  <Icon icon="simple-line-icons:settings" /> {{ t('批量人员分配') }}
                </a-button>
              </a-popover>
          </template>
        </BasicTable>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsMoOrderScOrderTaskForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed  } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  // import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  // import { ScOrder, scOrderAdjust } from '/@/api/mes/mo/order/scOrder';
  import { mesOrderTaskOperatorFp } from '/@/api/mes/mo/task/mesOrderTask';

  import { BasicTable, useTable } from '/@/components/Table';
  // import { InputTextArea } from '/@/components/Form';

  import { basOperatorTreeData } from '/@/api/bas/mes/operator/basOperator';
  const visible = ref<boolean>(false);
  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('mo.order.scOrder');
  const { showMessage } = useMessage();
  const record = ref<any>({});
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: t('任务分派人员'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      // label: t('计划开始'),
      field: 'task',
      component: 'Input',
      slot: 'taskList',
    },
  ];

  const schemas: FormSchema[] = [
    {
      field: 'operator',
      component: 'TreeSelect',
      label: t('操作工'),
      componentProps: {
        api: basOperatorTreeData,
          // ,isShowCode: true
        params: { isLoadUser: true, userIdPrefix: '' },
        canSelectParent: false,
        treeCheckable: true,
        immediate: true,
      },
    },
  ];

  const [registerForm, { validate, resetFields }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });
  const [registerOperateForm, { validate: validate1, resetFields: resetFields1 }] = useForm({
    labelWidth: 120,
    schemas: schemas,
    baseColProps: { lg: 24, md: 24 },
    submitButtonOptions: {
      text: '确定',
    },
    // 修改重置按钮文字
    resetButtonOptions: {
      text: '取消',
    },
    resetFunc: () => {
      console.log('resetFunc');
      handleBatchCancelInTable();
    },
    // 自动以重置按钮的方法
    showActionButtonGroup: true,
  });
  const [registertaskTable, taskTable] = useTable({
    // actionColumn: {
    //   width: 60,
    //   actions: (record: Recordable) => [
    //     {
    //       icon: 'ant-design:delete-outlined',
    //       color: 'error',
    //       popConfirm: {
    //         title: '是否确认删除',
    //         confirm: handleTestDataChildDelete.bind(this, record),
    //       },
    //       auth: 'test:testData:edit',
    //     },
    //   ],
    // },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    // size: 'small',
    inset: true,
    ellipsis: false,
  });
  const [registerDrawer, { closeDrawer, setDrawerProps }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    // await taskTable.setTableData([]);
    await resetFields();
    console.log(data, 'data===');
    record.value.arr = data.arr.map((item) => {
      item.operator = item.userCodes || '';
      return item;
    });
    record.value.__t = new Date().getTime();
    settaskChildTableData(record.value);
    setDrawerProps({ loading: false });
  });

  async function settaskChildTableData(_res: Recordable) {
    taskTable.setColumns([
      {
        title: t('操作工'),
        dataIndex: 'operator',
        width: 200,
        align: 'left',
        editRow: true,
        editable: true,
        editComponent: 'TreeSelect',
        editComponentProps: {
          api: basOperatorTreeData,
          params: { isLoadUser: true, userIdPrefix: '' },
          canSelectParent: false,
          treeCheckable: true,
          immediate: true,
        },
      },
      {
        title: t('分派人数'),
        dataIndex: 'taskPleNum',
        width: 200,
        align: 'left',
        editRow: true,
        editable: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          min: 0,
        },
      },
      {
        title: t('工序编码'),
        dataIndex: 'operCode',
        key: 'a.oper_code',
        sorter: true,
        width: 80,
        align: 'left',
      },
      {
        title: t('工序名称'),
        dataIndex: 'basOper.name',
        width: 150,
        align: 'left',
      },
      {
        title: t('存货编码'),
        dataIndex: 'invCode',
        key: 'a.inv_code',
        sorter: true,
        width: 130,
        align: 'left',
      },
      {
        title: t('存货名称'),
        dataIndex: 'basInv.cinvname',
        width: 200,
        align: 'left',
      },
      {
        title: t('规格型号'),
        dataIndex: 'basInv.cinvstd',
        width: 180,
        align: 'left',
      },
      {
        title: t('生产线'),
        dataIndex: 'fp.lineCode',
        width: 100,
        align: 'center',
      },
      {
        title: t('任务数量'),
        dataIndex: 'iqty',
        width: 80,
        align: 'center',
      },
    ]);
    taskTable.setTableData(record.value.arr || []);
  }

  function handletaskRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  async function gettaskTableChildList() {
    let taskTableChildListValid = true;
    let taskTableChildList: Recordable[] = [];
    for (const record of taskTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        taskTableChildListValid = false;
      }
      taskTableChildList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of taskTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      taskTableChildList.push({
        ...record,
        status: '1',
      });
    }
    if (!taskTableChildListValid) {
      throw { errorFields: [{ name: ['taskTableChildList'] }] };
    }
    return taskTableChildList;
  }

  async function handleSubmit() {
    try {
      // const data = await validate();
      // data.selIds = record.value.selIds;
      setDrawerProps({ confirmLoading: true });
      const data = {};
      data.list = await gettaskTableChildList();
      data.list.forEach((item) => {
        item.taskId = item.id;
        item.id = '';
        item.operator = item.editValueRefs.operator;
      });
      //console.log('submit', data);
      const res = await mesOrderTaskOperatorFp(data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
  // 选中操作工，把操作工分配给列表的操作工组件的值
  // 假设 handleSubmitOperateForm 方法已经被正确触发并能获取到选中的操作工数据
  async function handleSubmitOperateForm() {
    
    // 假设 validate1 是验证表单的方法，确保选中的操作工有效
    const isValid = await validate1();
    console.log('isValid', isValid);
    if (!isValid.operator) {
      showMessage(t('请选择有效的操作工'));
      return;
    }
    const formData = await validate1();
    const selectedOperators = formData.operator;
    const updatedTasks = taskTable.getDataSource().map(task => {
      // 根据您的需求决定如何处理操作工信息，这里简单地假设直接替换
      return {
        ...task,
        operator: selectedOperators, // 或者根据需要处理成其他格式
      };
    });
    taskTable.setTableData(updatedTasks);
    visible.value = false;
    console.log('visible after nextTick', visible.value);

  }

  const handleBatchCancelInTable = () => {
    const updatedTasks = taskTable.getDataSource().map(task => ({
      ...task,
      operator: '', // Reset the operator field for each task
    }));
    taskTable.setTableData(updatedTasks);
    visible.value = false;
    console.log('visible', visible.value);
  };

</script>
<style lang="less" scoped>
  :deep(.jeesite-editable-cell__action) {
    display: none;
  }
  :deep(.ant-popover-buttons) {
    display: none !important;
  }
</style>
